import { defineStore } from "pinia";
import { ref } from "vue";
import { reqGetChannelList, reqGetWithdrawalList } from "@/api/index";

export const useUserStore = defineStore("user", () => {
  const mail = ref("");
  const user_id = ref("");
  const token = ref("");

  const setUserInfo = (data) => {
    if (data?.token) {
      token.value = data.token;
      localStorage.setItem("token", data.token);
    } else {
      token.value = localStorage.getItem("token");
    }
    if (data?.mail) {
      mail.value = data.mail;
      localStorage.setItem("mail", data.mail);
    } else {
      mail.value = localStorage.getItem("mail");
    }
    if (data?.user_id) {
      user_id.value = data.user_id;
      localStorage.setItem("user_id", data.user_id);
    } else {
      user_id.value = localStorage.getItem("user_id");
    }
  };

  return { mail, user_id, setUserInfo };
});

// 下拉框选项相关数据
export const useSelectOptionsStore = defineStore("selectOptions", () => {
  // const channelList = ref([]);
  const agentPayMethodList = ref([]);
  const currencyList = ref([]);

  // const setChannelList = async () => {
  //   const storageChannelList = localStorage.getItem("channelList");
  //   if (storageChannelList) {
  //     channelList.value = JSON.parse(storageChannelList);
  //     return;
  //   }
  //   const res = await reqGetChannelList(localStorage.getItem("user_id"));
  //   clog("channelList:", res);
  //   channelList.value = res.data.map((item) => ({
  //     ...item,
  //     value: item.id,
  //     label: item.pay_type_code_name,
  //   }));
  //   localStorage.setItem("channelList", JSON.stringify(channelList.value));
  // };
  const setAgentPayMethodList = async () => {
    const storageAgentPayMethodList =
      localStorage.getItem("agentPayMethodList");
    if (storageAgentPayMethodList) {
      agentPayMethodList.value = JSON.parse(storageAgentPayMethodList);
      return;
    }
    const res = await reqGetWithdrawalList(localStorage.getItem("user_id"));
    clog("agentPayMethodList:", res);
    agentPayMethodList.value = res.data.map((item) => ({
      ...item,
      value: item.bank_id,
      label: item.bank_name,
    }));
    localStorage.setItem(
      "agentPayMethodList",
      JSON.stringify(agentPayMethodList.value)
    );
  };
  const setCurrencyList = (pCurrencies) => {
    const storageCurrenyList = localStorage.getItem("currencyList");
    if (storageCurrenyList) {
      currencyList.value = JSON.parse(storageCurrenyList);
      return;
    }
    if(!pCurrencies || pCurrencies.length === 0){
      return;
    }
    currencyList.value = pCurrencies.map((item) => ({
      ...item,
      label: item.currency,
      value: item.currency,
    }));
    clog("currencyList:", currencyList.value);
    localStorage.setItem("currencyList", JSON.stringify(currencyList.value));
  }
  return { currencyList, agentPayMethodList,setAgentPayMethodList,setCurrencyList };
});
